import {
	apiUrl,
	imageCompressSize,
    imgApiUrl
} from './config.js';
import * as common from './common.js' //引入common
import * as db from './db.js' //引入common
import Json from 'Json' //测试用数据

export const json = type=>{
	//模拟异步请求数据
	return new Promise(resolve=>{
		setTimeout(()=>{
			resolve(Json[type]);
		}, 500)
	})
}

// 不需要登陆的，都写到这里，否则就是需要登陆的接口
const methodsToken = [
	'public/registerCheck',
	'public/register',
	'public/login',
	'goods/homeClass',
	'goods/otherClass',
	'goods/goodsList',
	'goods/detail'
];



const url_get_dic = apiUrl + 'api/mall/';
const get = (url, params, callback) => {
	params = params || {}
	if(!params.__silent_mode__) {
		uni.showLoading({
			title: 'Loading'
		});
	}
	
	let header = {
		'Accept': 'application/json',
		'XX-Device-Type': 'app',
	}
	
	// 判断token是否存在
	if (methodsToken.indexOf(url) < 0) {
		// 获取用户token
		let userToken = db.get("userToken");
		if (!userToken) {
			common.jumpToLogin();
			return false;
		} else {
			// params.key = userKey;
			header['XX-Token'] = userToken;
		}
	}
	
	uni.request({
		url: url_get_dic + url,
		header: header,
		method: 'GET',
		data: params,
		success: (response) => {
			if(!params.__silent_mode__) {
				uni.hideLoading();
			}
			callback(response.data);
		},
		fail: (error) => {
			uni.hideLoading();
			if (error && error.response) {
				showError(error.response);
			}
		},
		complete: () => {
			setTimeout(function() {
				uni.hideLoading();
			}, 250);
		}
	});
}


const post = (method, data, callback,complete) => {
	uni.showLoading({
		title: 'Loading'
	});

	let header = {
		'Accept': 'application/json',
		'XX-Device-Type': 'app',
		'Content-Type': 'application/x-www-form-urlencoded', //自定义请求头信息
	}
	
	// 判断token是否存在
	if (methodsToken.indexOf(method) < 0) {
		// 获取用户token
		let userToken = db.get("userToken");
		if (!userToken) {
			common.jumpToLogin();
			return false;
		} else {
			if(!data.key) {
				data.key = userToken;
			}
			header['XX-Token'] = userToken;
		}
	}

	uni.request({
		url: url_get_dic + method,
		data: data,
		header: header,
		method: 'POST',
		success: (response) => {
			uni.hideLoading();
			const result = response.data
			if (result.code !== 1) {
				// 登录信息过期或者未登录
				if (result.login === '0') {
					db.del("userid");
					db.del("userToken");
					uni.showToast({
						title: result.message,
						icon: 'none',
						duration: 1000,
						complete: function() {
							setTimeout(function() {
								uni.hideToast();
								// #ifdef H5 || APP-PLUS || APP-PLUS-NVUE
								uni.navigateTo({
									url: '/pages/login/login'
								})
								// #endif
								// #ifdef MP-WEIXIN || MP-ALIPAY || MP-TOUTIAO
								
								uni.navigateTo({
									url: '/pages/login/login'
								})
								// uni.navigateTo({
								// 	url: '/pages/login/choose/index',
								// 	animationType: 'pop-in',
								// 	animationDuration: 200
								// });
								// #endif
							}, 1000)
						}
					});
				}
			}
			callback(result);
		},
		complete: (response) => {
			setTimeout(function() {
				uni.hideLoading();
			}, 1000)
			complete?complete(): "";
		},
		fail: (error) => {
			uni.showLoading({
				title: 'The internet is a little bit worse'
			});
			setTimeout(function() {
				uni.hideLoading();
			}, 1000)
			if (error && error.response) {
				showError(error.response);
			} else {
				
			}
			
		},
	});

}


const uploadPicker = function () {
	return new Promise(function (resolve, reject) {

		plus.nativeUI.actionSheet({
				cancel: 'Cancel',
				buttons: [{
					title: 'Camera'//相机国际化文字
				},
					{
						title: 'Photo album'//相册国际化文字
					}
				]
			},
			(tap) => {
				if (tap.index === 1) {
					let RearCamera = plus.camera.getCamera( 1 );
					RearCamera.captureImage((file)=>{
						// this.fileList = this.imgs = [file]
						resolve([file]);
					},(err)=>{
						console.log(err)
					},{"optimize":false})
				} else if (tap.index === 2) {
					plus.gallery.pick((res)=>{
						// this.fileList = this.imgs =  res.files
						resolve(res.files);
					},(err)=>{
						console.log(err)
					},{
						maximum:3,
						multiple:true
					});
				}
			})
	})
}

// 上传图片
export const upload_file = (url, data, name, callback) => {
	let header = {
		'Accept': 'application/json',
		'XX-Device-Type': 'app'
	}
	
	// 判断token是否存在
	if (methodsToken.indexOf(url) < 0) {
		// 获取用户token
		let userToken = db.get("userToken");
		if (!userToken) {
			common.jumpToLogin();
			return false;
		} else {
			header['XX-Token'] = userToken;
		}
	}

	uploadPicker().then((images) => {
			uni.showLoading({
				title: 'Uploading ...'
			});

			const tempFilePaths = images;
			
			// #ifdef APP-PLUS
			const imgList = []
			const taskList = []
			
			tempFilePaths.forEach((fileSrc, index) => {
				setFile(fileSrc, res => {
					const uploadTask = uni.uploadFile({
						url: apiUrl + url, //仅为示例，非真实的接口地址
						filePath: res,
						fileType: 'image',
						name: name,
						header: header,
						formData: data,
						success: (uploadFileRes) => {
							const imgData = JSON.parse(uploadFileRes.data)
							if(imgData.code === 1) {
								imgList.push(imgData.data.url)
							}
						},
						fail: (error) => {
							if (error && error.response) {
								showError(error.response);
							}
						},
						complete: () => {
							setTimeout(function() {
								uni.hideLoading();
							}, 250);
						}
					});
					
					taskList.push(uploadTask)
				})
			})
			
			Promise.all(taskList).then((result) => {
				callback(imgList);
			})
			// #endif
			
			// #ifdef H5
			const imgList = []
			const taskList = []
			
			tempFilePaths.forEach((fileSrc, index) => {
				const uploadTask = uni.uploadFile({
					url: apiUrl + url, //仅为示例，非真实的接口地址
					filePath: fileSrc,
					fileType: 'image',
					name: name,
					header: header,
					formData: data,
					success: (uploadFileRes) => {
						const imgData = JSON.parse(uploadFileRes.data)
						if(imgData.code === 1) {
							imgList.push(imgData.data.url)
						}
					},
					fail: (error) => {
						if (error && error.response) {
							showError(error.response);
						}
					},
					complete: () => {
						setTimeout(function() {
							uni.hideLoading();
						}, 250);
					}
				});
				taskList.push(uploadTask)
			})
			
			Promise.all(taskList).then((result) => {
				callback(imgList);
			})
			// #endif
	});
}

// 压缩图片文件
const setFile = (fileSrc, callback) => {
	var name = (new Date).getTime() + '_' + parseInt(Math.random() * 10000) + fileSrc.replace(/^.*(\.[^\.]*)$/, '$1');
	let fileArr = []
	//压缩取得缩略图
	plus.zip.compressImage({
		src: fileSrc,
		dst: '_downloads/' + name,
		overwrite: true,
		format: 'jpg',
		quality: imageCompressSize.quality,
		width: imageCompressSize.width,
		height: 'auto'
	}, function(zip) {
	   fileArr.push(zip.target);
	   callback(zip.target)
	}, function(zip) {
	});
}


const showError = error => {
	let errorMsg = ''
	switch (error.status) {
		case 400:
			errorMsg = 'Parameter Invalid'
			break
		case 401:
			errorMsg = 'Authentication Fail'
			break
		case 403:
			errorMsg = 'Access forbid'
			break
		case 404:
			errorMsg = `Request fail: ${error.config.url}`
			break
		case 408:
			errorMsg = 'Request Timeout'
			break
		case 500:
			errorMsg = 'Request Fail'
			break
		case 501:
			errorMsg = 'Service not found'
			break
		case 502:
			errorMsg = 'Network error'
			break
		case 503:
			errorMsg = 'Service not available'
			break
		case 504:
			errorMsg = 'Network Timeout'
			break
		case 505:
			errorMsg = 'HTTP version fail'
			break
		default:
			errorMsg = error.msg
			break
	}

	uni.showToast({
		title: errorMsg,
		icon: 'none',
		duration: 1000,
		complete: function() {
			setTimeout(function() {
				uni.hideToast();
			}, 1000);
		}
	});
}

export const default_user_portrait =  apiUrl + "uploads/home/common/default_user_portrait.gif" //默认图片,
// 字典查询
export const dictionary = (params, callback) => get('dictionary/query', params, callback);
// 首页
export const getIndex = (callback) => get('public/registerCheck', null, callback);
// 首页 - 轮播图
export const advList = (data, callback) => post('adv/index', data, callback);
// 注册 - 信息验证
export const registerCheck = (data, callback) => post('public/registerCheck', data, callback);
// 注册 - 信息提交
export const register = (data, callback) => post('public/register', data, callback);
// 用户 - 登录
export const login = (data, callback) => post('public/login', data, callback);
// 用户 - 退出
export const logout = (callback) => post('public/logout', {}, callback);
// 用户信息修改 - 用户名
export const changeName = (data, callback) => post('public/changeUserData', data, callback);
// 商品分类 - 首页数据
export const homeClass = (callback) => get('goods/homeClass', null, callback);
// 商品分类 - 其它数据
export const otherClass = (callback) => get('goods/otherClass', null, callback);
// 商品分类 - 列表
export const goodsList = (params, callback) => get('goods/goodsList', params, callback);
// 商品分类 - 列表
export const goodsDetail = (params, callback) => get('goods/detail', params, callback);
// 收件地址 - 列表
export const addressList = (params, callback) => get('address/index', params, callback);
// 收件地址 - 添加/编辑
export const addressSave = (data, callback) => post('address/save', data, callback);
// 收件地址 - 详情
export const addressDetail = (params, callback) => get('address/detail', params, callback);
// 收件地址 - 删除
export const addressDel = (data, callback) => post('address/del', data, callback);
// 购物车 - 列表
export const cartList = (callback) => get('cart/index', null, callback);
// 购物车 - 添加/编辑
export const cartSave = (data, callback) => post('cart/save', data, callback);
// 购物车 - 详情
export const cartDetail = (params, callback) => get('cart/detail', params, callback);
// 购物车 - 数量增加
export const cartIncrease = (data, callback) => post('cart/increase', data, callback);
// 购物车 - 数量减少
export const cartDecrease = (data, callback) => post('cart/decrease', data, callback);
// 购物车 - 删除
export const cartDel = (data, callback) => post('cart/del', data, callback);
// 订单创建 - Step 1
export const orderCreate = (data, callback) => post('buy/step1', data, callback);
// 订单创建 - Step 2
export const orderCreate_step2 = (data, callback) => post('buy/step2', data, callback);
// 订单 - 列表
export const orderList = (params, callback) => get('order/index', params, callback);
// 订单 - 删除
export const orderDel = (data, callback) => post('order/del', data, callback);
// 订单 - 删除
export const orderDetail = (data, callback) => get('order/detail', data, callback);
// 订单 - 退款
export const orderRefund = (data, callback) => post('order/UserOrderRefund', data, callback);
// 小区 - 列表
export const condominiumList = (params, callback) => get('condominium/index', params, callback);
// 消息 - 列表
export const messageList = (params, callback) => get('message/index', params, callback);
// 消息 - 已读
export const messageRead = (data, callback) => post('message/read', data, callback);
// 消息 - 删除
export const messageDel = (data, callback) => post('message/del', data, callback);
// 上传退款退货凭证
export const upload_refund_pic = (data, callback) => upload_file('api/user/data/upload.html', data, 'file', callback);
// 首页 - 有没有已读未读消息
export const newMessage = (data, callback) => post('message/new_message', data, callback);
// 首页 - 设置默认地址
export const saveDefaultAddr = (data, callback) => post('Address/saveDefaultAddr', data, callback);
